<template>

    <el-dialog
    title="添加商品信息"
    v-model="dialogVisible"
    width="30%"
    @close="closeDialog(false)">
    
        <el-form :model="ruleForm" :rules="rules" ref="ruleFormRef" label-width="100px" >
        <el-form-item label="商品名称" prop="name">
            <el-input v-model="ruleForm.name"></el-input>
        </el-form-item>
        <el-form-item label="图片" prop="pic">
            <el-upload 
            class="avatar-uploader"
            :action="uploadURL"
            :show-file-list="false"
            :before-upload="handleBeforeUpload">
            <i class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
        </el-form-item>
        <el-form-item label="活动区域" prop="region">
            <el-select v-model="ruleForm.region" placeholder="请选择活动区域">
            <el-option label="区域一" value="shanghai"></el-option>
            <el-option label="区域二" value="beijing"></el-option>
            </el-select>
        </el-form-item>

        <el-form-item label="上线时间" required>
            <el-col :span="11">
            <el-form-item prop="date1">
                <el-date-picker type="date" placeholder="选择日期" v-model="ruleForm.date1" style="width: 100%;"></el-date-picker>
            </el-form-item>
            </el-col>
            <el-col class="line" :span="2">-</el-col>
            <el-col :span="11">
            <el-form-item prop="date2">
                <el-time-picker placeholder="选择时间" v-model="ruleForm.date2" style="width: 100%;"></el-time-picker>
            </el-form-item>
            </el-col>
        </el-form-item>
        <el-form-item label="是否支持配送" prop="delivery">
            <el-switch v-model="ruleForm.delivery"></el-switch>
        </el-form-item>
        
        <el-form-item label="特殊资源" prop="resource">
            <el-radio-group v-model="ruleForm.resource">
              <el-radio label="线上品牌商赞助"></el-radio>
              <el-radio label="线下场地免费"></el-radio>
            </el-radio-group>
        </el-form-item>
        <el-form-item label="商家邮箱" prop="email">
             <el-input v-model="ruleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="商品描述" prop="desc">
            <el-input type="textarea" v-model="ruleForm.desc"></el-input>
        </el-form-item>
        <el-form-item label="商品详情" prop="goodDetial">
            <QuillEditor theme="snow" ref="editor"></QuillEditor>
        </el-form-item>
        </el-form>
    

    <template #footer>
        <span class="dialog-footer">
        <el-button @click="()=>{
                closeDialog(false);
            }">取 消</el-button>
        <el-button type="primary" @click="commitGood">确 定</el-button>
        </span>
    </template>
    </el-dialog>
</template>

<script>
import { reactive, ref, toRefs } from 'vue';
import {QuillEditor} from "@vueup/vue-quill";
import '@vueup/vue-quill/dist/vue-quill.snow.css';
import axios from 'axios';
import {ElMessage} from "element-plus";

function useAdd(closeDialogRef, editor,state, ruleFormRef){
       const commitGood = () => {alert(editor.value.getHTML());
          state.ruleForm.goodDetial =editor.value.getText().replace(/(\r\n|\n|\r)/gm,'<br />')!=="<br />" ? editor.value.getHTML():"";
          ruleFormRef.value.validate((valid)=>{
            if(!valid)
            {
                console.log(valid);
            }
            else
            {
              // 整理要传向后台的数据
                const params = {
                  name: state.ruleForm.name,
                  detail: state.ruleForm.goodDetial,
                  desc: state.ruleForm.desc
                };
                axios.post("/add/goods", params).then(res=>{
                  ruleFormRef.value.resetFields();
                  editor.value.setText("");
                  console.log(res.data);
                  closeDialogRef(false, res.data);
                })
            }
          })
          
          alert(JSON.stringify(state.ruleForm));
        };
        return {
          commitGood,
        };
}

//文件类型校验

const handleBeforeUpload=(file)=>{
  const fileType = file.name.split('.')[1]
  console.log(fileType);
  if(!['jpg','jpeg','png'].includes(fileType)){
    ElMessage.error("jpg,jpeg,png");
    return false;
  }
}
function useCheckEmail(){
  const checkMail=(rule, value, cb)=>{
    const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
    if(regEmail.test(value)){
      return cb();
    }

    cb(new Error("email not validate"));
  }

  return {
    checkMail
  }
}
export default {
    components:{
      QuillEditor
    },

    emits:["onCloseDialog"],

    setup(props, { emit }){
        const ruleFormRef = ref();
        const editor = ref();
        const state = reactive
        ({
            dialogVisible:true,
  
            ruleForm: {
                name: '',
                region: '',
                date1: '',
                date2: '',
                delivery: false,
                type: [],
                resource: '',
                desc: '',
                goodDetial:'',
                pic:'',
                email:''
            },
    
        });
          const uploadURL="your_upload_url";

          const rules = {
          name: [
            { required: true, message: '请输入活动名称', trigger: 'blur' },
            { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
          ],
          region: [
            { required: false, message: '请选择活动区域', trigger: 'change' }
          ],
          date1: [
            { type: 'date', required: false, message: '请选择日期', trigger: 'change' }
          ],
          date2: [
            { type: 'date', required: false, message: '请选择时间', trigger: 'change' }
          ],
          type: [
            { type: 'array', required: false, message: '请至少选择一个活动性质', trigger: 'change' }
          ],
          resource: [
            { required: false, message: '请选择活动资源', trigger: 'change' }
          ],
          desc: [
            { required: true, message: '请填写活动形式', trigger: 'blur' }
          ],
          goodDetial: [
            { required: true, message: '请填商品细节', trigger: 'blur' }
          ],
          email:[
            { required: true, message: '请填邮箱', trigger: 'blur' },
            {
              validator:useCheckEmail().checkMail,trigger: 'blur'
            }
          ]
        }

        const closeDialog = (visible, oneGoods)=>{
            emit('onCloseDialog', visible, oneGoods);
        };
        
        return{
            rules,
            ruleFormRef,
            uploadURL,
            editor,
            closeDialog,
            ...toRefs(state),
            ...useAdd(closeDialog, editor,state,ruleFormRef),
            handleBeforeUpload,
        }
    }
};
</script>

<style>

</style>
